package com.zenithmind.mall.pojo.entity;

import com.baomidou.mybatisplus.annotation.TableName;
import com.zenithmind.common.base.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 优惠券实体
 * 
 * @author ZenithMind Team
 * @since 2025-06-09
 */
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("mall_coupon")
public class Coupon extends BaseEntity {

    /**
     * 优惠券名称
     */
    private String name;

    /**
     * 优惠券描述
     */
    private String description;

    /**
     * 优惠券类型（1-满减券，2-折扣券，3-免邮券）
     */
    private Integer type;

    /**
     * 优惠券面值
     */
    private BigDecimal amount;

    /**
     * 折扣率（折扣券使用，如0.8表示8折）
     */
    private BigDecimal discountRate;

    /**
     * 使用门槛（满多少可用）
     */
    private BigDecimal minAmount;

    /**
     * 发放总数
     */
    private Integer totalCount;

    /**
     * 已领取数量
     */
    private Integer receivedCount;

    /**
     * 已使用数量
     */
    private Integer usedCount;

    /**
     * 每人限领数量
     */
    private Integer limitPerUser;

    /**
     * 有效期开始时间
     */
    private LocalDateTime startTime;

    /**
     * 有效期结束时间
     */
    private LocalDateTime endTime;

    /**
     * 状态（0-未开始，1-进行中，2-已结束，3-已停用）
     */
    private Integer status;

    /**
     * 适用商品类型（0-全部商品，1-指定分类，2-指定商品）
     */
    private Integer applicableType;

    /**
     * 适用商品ID列表（JSON格式）
     */
    private String applicableProducts;

    /**
     * 适用分类ID列表（JSON格式）
     */
    private String applicableCategories;

    // 业务方法

    /**
     * 检查优惠券是否为满减券
     */
    public boolean isFullReductionCoupon() {
        return Objects.equals(this.type, 1);
    }

    /**
     * 检查优惠券是否为折扣券
     */
    public boolean isDiscountCoupon() {
        return Objects.equals(this.type, 2);
    }

    /**
     * 检查优惠券是否为免邮券
     */
    public boolean isFreeShippingCoupon() {
        return Objects.equals(this.type, 3);
    }

    /**
     * 检查优惠券是否未开始
     */
    public boolean isNotStarted() {
        return Objects.equals(this.status, 0);
    }

    /**
     * 检查优惠券是否进行中
     */
    public boolean isActive() {
        return Objects.equals(this.status, 1);
    }

    /**
     * 检查优惠券是否已结束
     */
    public boolean isEnded() {
        return Objects.equals(this.status, 2);
    }

    /**
     * 检查优惠券是否已停用
     */
    public boolean isDisabled() {
        return Objects.equals(this.status, 3);
    }

    /**
     * 检查优惠券是否在有效期内
     */
    public boolean isInValidPeriod() {
        LocalDateTime now = LocalDateTime.now();
        return (startTime == null || !now.isBefore(startTime)) &&
               (endTime == null || !now.isAfter(endTime));
    }

    /**
     * 检查优惠券是否可用
     */
    public boolean isAvailable() {
        return isActive() && isInValidPeriod() && hasStock();
    }

    /**
     * 检查优惠券是否有库存
     */
    public boolean hasStock() {
        if (totalCount == null || totalCount <= 0) {
            return true; // 无限制
        }
        int received = receivedCount != null ? receivedCount : 0;
        return received < totalCount;
    }

    /**
     * 检查用户是否可以领取（不考虑个人限制）
     */
    public boolean canReceive() {
        return isAvailable() && hasStock();
    }

    /**
     * 检查订单金额是否满足使用条件
     */
    public boolean canUseForAmount(BigDecimal orderAmount) {
        if (orderAmount == null) {
            return false;
        }
        if (minAmount == null || minAmount.compareTo(BigDecimal.ZERO) <= 0) {
            return true; // 无门槛
        }
        return orderAmount.compareTo(minAmount) >= 0;
    }

    /**
     * 计算优惠金额
     */
    public BigDecimal calculateDiscountAmount(BigDecimal orderAmount) {
        if (!canUseForAmount(orderAmount)) {
            return BigDecimal.ZERO;
        }

        if (isFullReductionCoupon()) {
            return amount != null ? amount : BigDecimal.ZERO;
        } else if (isDiscountCoupon()) {
            if (discountRate != null && discountRate.compareTo(BigDecimal.ZERO) > 0 &&
                discountRate.compareTo(BigDecimal.ONE) < 0) {
                BigDecimal discount = orderAmount.multiply(BigDecimal.ONE.subtract(discountRate));
                // 如果有最大优惠金额限制
                if (amount != null && discount.compareTo(amount) > 0) {
                    return amount;
                }
                return discount;
            }
        } else if (isFreeShippingCoupon()) {
            // 免邮券的优惠金额需要根据实际运费计算
            return BigDecimal.ZERO;
        }

        return BigDecimal.ZERO;
    }

    /**
     * 增加领取数量
     */
    public boolean increaseReceivedCount() {
        if (!hasStock()) {
            return false;
        }
        this.receivedCount = (this.receivedCount != null ? this.receivedCount : 0) + 1;
        return true;
    }

    /**
     * 增加使用数量
     */
    public void increaseUsedCount() {
        this.usedCount = (this.usedCount != null ? this.usedCount : 0) + 1;
    }

    /**
     * 获取剩余数量
     */
    public Integer getRemainingCount() {
        if (totalCount == null || totalCount <= 0) {
            return null; // 无限制
        }
        int received = receivedCount != null ? receivedCount : 0;
        return Math.max(0, totalCount - received);
    }

    /**
     * 获取使用率
     */
    public Double getUsageRate() {
        int received = receivedCount != null ? receivedCount : 0;
        if (received == 0) {
            return 0.0;
        }
        int used = usedCount != null ? usedCount : 0;
        return (double) used / received;
    }

    /**
     * 验证优惠券数据完整性
     */
    public boolean isValid() {
        return name != null && !name.trim().isEmpty() &&
               type != null && type >= 1 && type <= 3 &&
               status != null && status >= 0 && status <= 3 &&
               (amount != null || discountRate != null) &&
               (totalCount == null || totalCount > 0) &&
               (limitPerUser == null || limitPerUser > 0);
    }
}
